// pages/tabbar/home/index.ts
import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from "~/stores/app"
import { doBanner, doStatistics, doHighQuality } from '~/api/home'
import { deepClone } from '~/utils/util'
import * as watch from '~/utils/watch'
import type { itemState } from '~/../typings/types/city'
import type { SwiperList } from '~/../typings/types/home'
// import type { SwiperList } from 'tdesign-miniprogram/miniprogram_dist/swiper/type'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    swiperList: [] as SwiperList[],
    curren: 0 as number,
    starCity: [
      {
        "value": "320000",
        "label": "江苏省",
        "pinYin": "J",
        "description": ""
      }, {
        "value": "320300",
        "label": "徐州市",
        "pinYin": "X",
        "description": "18913477800"
      }] as itemState[],
    starCityName: '徐州市',
    endCity: [] as itemState[],
    endCityName: '',
    countInfo: {
      queriesNumber: 0,
      consultationNumber: 0
    },
    dialogKey: '' as string,
    keyName: '',
    horList: []
  },
  searchChange(e: any) {
    let dialogHome = this.dialogHome
    dialogHome.close()  // 调用自定义组件中的方法
    wx.navigateTo({
      url: `/pages/search/result?city=${encodeURIComponent(JSON.stringify(e))}`
    })
  },
  keyNameChange(e: WechatMiniprogram.Input) {
    this.setData({
      keyName: e.detail.value
    })
  },
  handSearchCity() {
    const { keyName } = this.data
    if (!keyName) {
      wx.showToast({
        icon: 'none',
        title: '请输入公司名称'
      })
      return
    }
    wx.navigateTo({
      url: `/pages/search/company/company?keyWord=${keyName}`
    })
  },
  //  城市卡片
  currenChange(this: any, e: any) {
    this.setData({
      curren: e.detail.value
    })
  },
  handOut(this: any) {
    wx.navigateTo({
      url: '/pages/city/index?type=star',
      events: {
        chooseEvent: (e: itemState[]) => {
          const info = e[e.length - 1];
          this.setData({
            starCity: e,
            starCityName: info?.label
          })
        }
      }
    })
  },
  handEnd(this: any) {
    const { starCity } = this.data
    const star = deepClone(starCity).map((el: itemState) => {
      return el.label
    }).join('-')
    const item = {
      star
    }
    console.log(item)

    wx.navigateTo({
      url: `/pages/city/index?type=end&city=${encodeURIComponent(JSON.stringify(item))}`,
      events: {
        chooseEvent: (e: itemState[]) => {
          const info = e[e.length - 1];
          if (['北京', '重庆', '天津', '上海'].includes(e[0].label)) {
            info.label = e[0].label
          }
          this.setData({
            endCity: e,
            endCityName: info?.label
          })
        }
      }
    })
  },
  handSearch() {
    const { starCityName, endCityName, starCity, endCity } = this.data
    if (!starCityName) {
      wx.showToast({
        icon: 'none',
        title: '请选择出发城市'
      })
      return
    }
    if (!endCityName) {
      wx.showToast({
        icon: 'none',
        title: '请选择目的地'
      })
      return
    }
    const star = deepClone(starCity).map((el: itemState) => {
      return el.label
    }).join('-')
    const end = deepClone(endCity).map((el: itemState) => {
      return el.label
    }).join('-')
    const item = {
      star,
      end
    }
    wx.navigateTo({
      url: `/pages/search/result?city=${encodeURIComponent(JSON.stringify(item))}`
    })
  },
  //  数量统计
  async initNums(this: any) {
    const data = await doStatistics()
    this.setData({
      countInfo: data
    })
  },
  //  轮播图
  clickSwiper(e: any) {
    const info: SwiperList = this.data.swiperList[e.detail.index]
    if (info?.link) {
      wx.navigateTo({
        url: info.link
      })
    }
  },
  async getBanner(this: any, code: string) {
    const data = await doBanner(code)
    this.setData({
      swiperList: data.list.map((el: any) => {
        el.value = el.url
        return el
      })
    })
  },
  async getHor(this: any) {
    const data = await doHighQuality({
      pageSize: 8,
      serviceSite: this.data.cityName
    })
    this.setData({
      horList: data
    })
  },
  // 城市切换
  handCity(this: any) {
    wx.navigateTo({
      url: '/pages/city/index?type=homeTop',
      events: {
        chooseEvent: (e: itemState[]) => {
          this.setCityArr(e)
        }
      }
    })
  },
  handMusic(this: any) {
    this.initMusic()
    this.dialogHome.open()
  },
  handGoCreate() {
    wx.switchTab({
      url: '/pages/tabbar/order/index'
    })
  },
  handDetail(e: any) {
    const dataset = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/shop/detail/detail?id=${dataset.id}`
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(this: any) {
    this.storeBinding = createStoreBindings(this, {
      store,
      fields: {
        cityName: 'getCityName',
        cityCode: 'getCityCode',
        recordState: 'getRecordState',
        searchInfo: 'getSearchInfo',
      },
      actions: ['setCityArr', 'initMusic']
    });
    watch.setWatcher(this);
    this.initNums()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady(this: any) {
    this.dialogHome = this.selectComponent("#dialogHome");
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload(this: any) {
    this.storeBinding.destroyStoreBindings();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  watch: {
    cityCode: function (newCode: string) {
      this.getBanner(newCode)
      this.getHor()
    },
    searchInfo: function (e: any) {
      const pages = getCurrentPages()
      if (e.star && pages.length > 0) {
        const path = pages[pages.length - 1].route
        if (path === 'pages/tabbar/home/index') {
          this.searchChange(e)
        }
      }
    },
  }
})